﻿
function GetGMarkerByID(markerID) {
	for (i = 0; i < gMarkers.length; i++) {
		if (gMarkers[i].Marker.ID == markerID) {
			return gMarkers[i];
		}
	}
}

function MoveToSelectedMarker() {
	var value = event.srcElement.value;
	var marker = GetGMarkerByID(value);
	if (marker != null)
		map.panTo(marker.getLatLng());
}

function e(id) {
	return document.getElementById(id);
}

// Return the window height
function getWindowHeight() {
	if (window.self && self.innerHeight) {
		return self.innerHeight;
	}
	if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	}
	if (document.body && document.body.clientHeight) {
		return windowHeight = document.body.clientHeight;
	}
	return 0;
}
// Return the window width
function getWindowWidth() {
	if (window.self && self.innerWidth) { return self.innerWidth; }
	if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	}
	return 0;
}

// Resize based off Googles code.
function resizeMapDiv() {
	var offsetTop = 0;
	var mapDiv = document.getElementById("map_canvas");
	for (var elem = mapDiv; elem; elem = elem.offsetParent) {
		offsetTop += elem.offsetTop;
	}
	//var height = getWindowHeight() - offsetTop - 10;
	var height = getWindowHeight() - offsetTop - 1;
	//alert("values gWH = " + getWindowHeight() + ", offsetTop=" + offsetTop);
	if (height >= 0) {
		mapDiv.style.height = height + "px";
		//alert("setting map height to " + height);
	}
	var offsetLeft = 0;
	var rDiv = document.getElementById("left");
	//if (isVisible(rDiv)) 
	{
		offsetLeft = rDiv.clientWidth;
	}
	//mapDiv.style.left = offsetLeft + "px";
	
	var width = getWindowWidth() - offsetLeft - 1; // This works on IE, FF & Opera
	if (width >= 0) {
		var conDiv = document.getElementById("container");
		mapDiv.style.width = width + "px";
		//conDiv.style.width = width + "px";
	}

	// If the map has been created at this point then resize and alter accordingly
	if (map) { map.checkResize(); }
}
    
   



//Google maps object
var map = null;
var geocoder = null;
var markerToMove = null;

//Markers array
var gMarkers = new Array();

//Initialize google maps control
function initialize() {

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GOverviewMapControl());
		//map.enableGoogleBar();
		map.enableScrollWheelZoom();
		map.addControl(new GScaleControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		//map.addControl(new GHierarchicalMapTypeControl());
		map.setCenter(new GLatLng(54.6, 39.6), 11);
		geocoder = new GClientGeocoder();

		resizeMapDiv();
	}
	LoadMarkers();
}


//Load markers
function LoadMarkers() {
	var gameID = e("ddlGames").value;
	//Get last markers positions 
	ret = NWS.AJAXService.GetPoints(gameID, MarkersRecieved);
	setTimeout("LoadMarkers()", document.getElementById('ddlDelay').value);
}

//Process markers array
function MarkersRecieved(markers) {
	DeleteUnusedMarkers(markers);

	//Go over the markers recieved from server
	for (i = 0; i < markers.length; i++) {
		var marker = markers[i];
		var curGMarker = null;
		//Sys.Debug.trace(marker);
		exists = false;
		//Go over the gmarkers on page
		for (j = 0; j < gMarkers.length; j++) {
			var gMarker = gMarkers[j];
			if (gMarker.Marker.ID == marker.ID) {
				exists = true;
				gMarker.Marker = marker;
				curGMarker = gMarker;
				break;
			}
		}
		if (!exists)//Create new marker
		{
			gMarkers.push(GreateGMarker(marker));
		}
		else//Move existing marker
		{
			curGMarker.setLatLng(new GLatLng(marker.Latitude, marker.Longitude));
		}
	}
}

//Create GMarker using marker data 
function GreateGMarker(marker) {
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon();
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34 + 15);
	baseIcon.shadowSize = new GSize(37, 34 + 15);
	baseIcon.iconAnchor = new GPoint(9, 34 + 15);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25 + 15);

	// Creates a marker whose info window displays the letter corresponding
	// to the given index.
	// Create a lettered icon for this point using our icon class

	var letter = marker.Name.charAt(0);
	if ((letter < 'A' || letter > 'Z') && (letter < 'a' || letter > 'z'))
		letter = "";


	var letteredIcon = new GIcon(baseIcon);
	//letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
	letteredIcon.image = "photo.aspx?id=" + marker.ID;

	// Set up our GMarkerOptions object
	markerOptions = { icon: letteredIcon };
	//create structure of marker parameters 
	options = { icon: letteredIcon, title: marker.Name, draggable: true, clickable: true };
	//create marker
	var gMarker = new GMarker(new GLatLng(marker.Latitude, marker.Longitude), options);
	gMarker.Marker = marker;
	map.addOverlay(gMarker);
	//add event handlers
	GEvent.addListener(gMarker, "dragend", function() { MoveMarker(gMarker) });
	GEvent.addListener(gMarker, "dragstart", function() { map.closeInfoWindow(); });
	GEvent.addListener(gMarker, "click", function() { ShowInfo(gMarker); });
	return gMarker;
}


//Move marker to current gMarker position 
function MoveMarker(gMarker) {
	//alert(gMarker.getTitle());
	ret = NWS.AJAXService.AddPoint(gMarker.Marker.ID, gMarker.getLatLng().lat(), gMarker.getLatLng().lng())
}

//Show HTML info window with information about marker
function ShowInfo(gMarker) {
	var info = NWS.AJAXService.GetMarkerDescription(gMarker.Marker.ID, MarkerDescriptionRecieved, MarkerDescriptionRecieved, gMarker);
}

function MarkerDescriptionRecieved(info, gMarker) {
	gMarker.openInfoWindowHtml(info);
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function ShowLocation() {
	var address = document.getElementById('tbSearch').value;
	geocoder.getLocations(address, AddAddressToMap);
}


// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function AddAddressToMap(response) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	}
	else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
		options = { title: response.name, clickable: true };
		var marker = new GMarker(point, options);
		map.addOverlay(marker);
		GEvent.addListener(marker, "click", function() { map.removeOverlay(marker) });
		coords = point.toUrlValue();
		marker.openInfoWindowHtml(response.name + '<br>' + place.address + '<br>' + coords);
	}
}

function SetMarkersOnLocation() {
	var address = document.getElementById('tbSearch').value;
	geocoder.getLocations(address, LocateMarkers);
}

function LocateMarkers(response) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	}
	else {
		var value = document.getElementById('lbMarkers').value;
		if (value == '')
			return;

		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);

		NWS.AJAXService.AddPoint(value, point.lat(), point.lng())

		var gMarker = GetGMarkerByID(value);
		if (gMarker != null) {
			gMarker.setLatLng(point);
		}
	}
}

function DeleteUnusedMarkers(markers) {
	//Go over the markers recieved from server
	for (i = gMarkers.length - 1; i >= 0; i--) {
		var gMarker = gMarkers[i];
		//Sys.Debug.trace(marker);
		exists = false;
		//Go over the markers on page
		for (j = 0; j < markers.length; j++) {
			if (gMarker.Marker.ID == markers[j].ID) {
				exists = true;
				break;
			}
		}
		if (!exists)//Create new marker
		{
			map.removeOverlay(gMarker);
			gMarkers.pop(gMarker);
		}
	}
}
    